﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;

namespace GameView.Comment
{
    public static class JsonSerializerSettings
    {
        public static JsonSerializerOptions DefaultOptions => new()
        {
            DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
            PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
            WriteIndented = true
        };
        public static JsonSerializerOptions DateTimeConverter => new()
        {
            Converters = {  new DateTimeConverter() },
            PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
            WriteIndented = true
        };
    }

    // 忽略0值的转换器
    public class ZeroIgnoringConverter : JsonConverterFactory
    {
        public override bool CanConvert(Type typeToConvert) =>
            typeToConvert == typeof(int) ||
            typeToConvert == typeof(uint) ||
            typeToConvert == typeof(long) ||
            typeToConvert == typeof(ulong) ||
            typeToConvert == typeof(float) ||
            typeToConvert == typeof(double) ||
            typeToConvert == typeof(decimal);

        public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options)
        {
            return (JsonConverter)Activator.CreateInstance(
                typeof(ZeroIgnoringConverter<>).MakeGenericType(typeToConvert));
        }
    }

    public class ZeroIgnoringConverter<T> : JsonConverter<T> where T : struct
    {
        public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            return JsonSerializer.Deserialize<T>(ref reader, options);
        }

        public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
        {
            if (!EqualityComparer<T>.Default.Equals(value, default))
            {
                JsonSerializer.Serialize(writer, value, options);
            }
        }
    }

    // 时间格式转换器
    public class DateTimeConverter : JsonConverter<DateTime>
    {
        public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            return DateTime.Parse(reader.GetString());
        }

        public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
        {
            writer.WriteStringValue(value.ToString("yyyy-MM-dd HH:mm:ss"));
        }
    }
}
